package service;

import api.LoginApi;
import bean.getUserInfo.GetUserInfoResponseBean;
import bean.getUserInfo.UserInfo;
import bean.login.LoginResponseBean;
import com.google.common.collect.ImmutableMap;
import common.pojo.CommonResult;
import common.spring.redis.RedisUnits;
import common.utils.CommomRandom;
import common.utils.JsonUtils;
import common.utils.MyMapUtils;
import common.utils.ObjectId;
import httpclient.HttpClientUtils;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pojo.WxUserInfo;
import service.cfg.RedisCfg;
import service.cfg.ServerCfg;
import service.cfg.UserShopCfg;


import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * Created by asus on 2018/10/6.
 */
@Service
public class LoginService {
    private final Logger LOG = LoggerFactory.getLogger(LoginService.class);

    @Autowired
    RedisUnits redisUnits;

    @Autowired
    LoginApi loginApi;

    @Autowired
    RedisCfg redisCfg;

    @Autowired
    ServerCfg serverCfg;

    @Autowired
    WxUserInfoService infoService;
    public CommonResult login(Map map,String parentOpenId,String recommendOpenId) {
        String code = map.get("code").toString();
        if (StringUtils.isBlank(code)) {
            return CommonResult.returnFailsWrapper("登录失败");
        }
        String detail = map.get("detail").toString();
        GetUserInfoResponseBean responseBean = JsonUtils.JsonToPojo(detail, GetUserInfoResponseBean.class);
        if (responseBean == null) {
            LOG.warn("---responseBean is null-");
            return CommonResult.returnFailsWrapper("用户信息获取失败");
        }
        if(map.get("agentId")!=null && StringUtils.isNotBlank(map.get("agentId").toString()) && NumberUtils.toLong(map.get("agentId").toString())>0){
            responseBean.getUserInfo().setAgentId(NumberUtils.toLong(map.get("agentId").toString()));
            responseBean.getUserInfo().setDeptId(0L);
        }else {
            if(parentOpenId.equals("clkj")){
                responseBean.getUserInfo().setAgentId(0L);
                responseBean.getUserInfo().setDeptId(0L);
            }else {
                WxUserInfo user = infoService.getWxUserInfo(parentOpenId);
                if(user==null){
                    responseBean.getUserInfo().setAgentId(0L);
                    responseBean.getUserInfo().setDeptId(0L);
                }else {
                    responseBean.getUserInfo().setAgentId(user.getAgentId());
                    responseBean.getUserInfo().setDeptId(user.getDeptId());
                }
            }
        }
        //获取openId
        try {
            LoginResponseBean info = loginApi.getLoginInfo(code);
            if (info.getErrcode() == 0) {
                //openId获取成功，将用户信息存入数据库
                responseBean.getUserInfo().setOpenId(info.getOpenid());
                if(StringUtils.isBlank(parentOpenId)){
                    parentOpenId="clkj";
                }
                responseBean.getUserInfo().setParentOpenId(parentOpenId);
               int t = infoService.addWxUserInfo(responseBean.getUserInfo());
               if(t<=0){
                   return CommonResult.returnFailsWrapper("身份信息添加失败");
               }
               if(StringUtils.isNotBlank(recommendOpenId)){
                   infoService.updateRecommendOpenId(recommendOpenId,info.getOpenid());
               }
                //将openId session_key 存入redis 并设置有效时间
                String UUID = CommomRandom.uuId();
                boolean bool = redisUnits.setMap(UUID, ImmutableMap.of("openId", info.getOpenid(), "sessionKey", info.getSession_key()),redisCfg.getDay());
                LOG.warn("---uuid----"+UUID);
                if(bool){
                    Map param = new HashMap();
                    param.put("uuid",UUID);
                    return CommonResult.returnDataWrapper(param).setTransientData(ImmutableMap.of("openId",info.getOpenid(),"headUrl",responseBean.getUserInfo().getAvatarUrl()));
                }else {
                    return CommonResult.returnFailsWrapper("用户信息写入redis失败");
                }

            } else {
                LOG.warn("---openId获取失败---" + info.getErrMsg());
                return CommonResult.returnFailsWrapper("用户信息获取失败");
            }
        } catch (Exception e) {
            LOG.warn("---用户信息获取错误exception---" +e.toString());
            return CommonResult.returnFailsWrapper("用户信息获取失败");
        }
    }


    public static void main(String[] str) {
        Map map = new HashMap();
        map.put("bsId", "qy_luozs");
        map.put("userId", "oPQnc4hfKj3Mynqmt9ad1yI3HaDI");
        map.put("name", "挥舞");
        map.put("mobile","15287471441");
        map.put("gender",3);
        map.put("avatar","https://wx.qlogo.cn/mmopen/vi_32/kux7T7XFj1V5U98oJSKxa8kWhfWlT4zibTeET8icg3qz8ADQ2MrjIPd6b1icxFXtWDc0xLU2Efpfbtdl9ibK6kWesw/132");

        String key="abc";//签名密钥
        String timestamp=String.valueOf(new Date().getTime());//距离1970年的时间戳
        String nonce= new ObjectId().toString(); //随机数

        List<String> tmpList = new ArrayList<>(); //三个参数加入list中
        tmpList.add(key);
        tmpList.add(timestamp);
        tmpList.add(nonce);
        Collections.sort(tmpList);  //三个参数按照字典排序
        //待签名字符串
        String tmpStr = StringUtils.join(tmpList.toArray()); //排序后list的三个参数join成字符串
        String signature="";
        try {
            //以SHA1的算法对tmpStr(代签名字符串)进行签名，得到签名(signature)
            signature= Hex.encodeHexString(MessageDigest.getInstance("SHA-1").digest(tmpStr.getBytes("UTF-8")));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url="http://ai.yncljk.com/qywx-api/wx/user/del?_timestamp="+timestamp+"&_nonce="+nonce+"&_signature="+signature;
        CommonResult commonResult = HttpClientUtils.post(url,map);
        System.out.println();
    }

}
